using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model.Plan;

namespace WPF_MVVM_Test.Services.Plan
{
    public class BomService : IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        private const string BASE_URL = "http://8.140.242.140:8888/api/Bom/paged";

        public BomService()
        {
            _httpClient = new HttpClient();
            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            };
        }

        public async Task<(List<BomModel> boms, int totalCount, int totalPage)> GetBomsAsync(int pageIndex = 1, int pageSize = 20, string productName = "", string bomNumber = "")
        {
            try
            {
                var query = $"pageIndex={pageIndex}&pageSize={pageSize}";
                if (!string.IsNullOrWhiteSpace(productName))
                    query += $"&productName={Uri.EscapeDataString(productName)}";
                if (!string.IsNullOrWhiteSpace(bomNumber))
                    query += $"&bomNumber={Uri.EscapeDataString(bomNumber)}";
                var requestUrl = $"{BASE_URL}?{query}";
                var response = await _httpClient.GetAsync(requestUrl);
                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonSerializer.Deserialize<BomApiResponse>(jsonContent, _jsonOptions);
                    if (apiResponse?.IsSuc == true && apiResponse.Data?.Data != null)
                    {
                        // 转换为BomModel列表
                        var boms = new List<BomModel>();
                        int index = (pageIndex - 1) * pageSize + 1;
                        foreach (var item in apiResponse.Data.Data)
                        {
                            boms.Add(new BomModel
                            {
                                Index = index++,
                                Id = item.id,
                                BomCode = item.bomNumber,
                                Version = item.version,
                                IsDefaultBom = item.isDefault ? "是" : "否",
                                Quantity = (int)item.dailyOutput,
                                IsSystemNumber = item.isSystemNumber,
                                ProductId = item.productId,
                                ProductName = item.productName,
                                ColorCode = item.colorCode,
                                Unit = item.unit,
                                DailyOutput = item.dailyOutput,
                                Remark = item.remark,
                                ProcessRouteId = item.processRouteId,
                                ProcessRouteName = item.processRouteName,
                                CreatedTime = item.createdTime,
                                LastUpdatedTime = item.lastUpdatedTime,
                                ItemCount = item.itemCount
                            });
                        }
                        return (boms, apiResponse.Data.TotalCount, apiResponse.Data.TotalPage);
                    }
                    else
                    {
                        throw new Exception($"API返回错误: {apiResponse?.Msg ?? "未知错误"}");
                    }
                }
                else
                {
                    throw new Exception($"API请求失败: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"❌ BOM API请求异常: {ex.Message}");
                return (new List<BomModel>(), 0, 0);
            }
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }

    // 用于反序列化API响应
    public class BomApiResponse
    {
        public BomApiData? Data { get; set; }
        public bool IsSuc { get; set; }
        public int Code { get; set; }
        public string Msg { get; set; } = string.Empty;
    }
    public class BomApiData
    {
        public int TotalCount { get; set; }
        public int TotalPage { get; set; }
        public List<BomApiItem>? Data { get; set; }
    }
    public class BomApiItem
    {
        public string id { get; set; } = string.Empty;
        public string bomNumber { get; set; } = string.Empty;
        public bool isSystemNumber { get; set; }
        public bool isDefault { get; set; }
        public string version { get; set; } = string.Empty;
        public string productId { get; set; } = string.Empty;
        public string productName { get; set; } = string.Empty;
        public string colorCode { get; set; } = string.Empty;
        public string unit { get; set; } = string.Empty;
        public decimal dailyOutput { get; set; }
        public string remark { get; set; } = string.Empty;
        public string processRouteId { get; set; } = string.Empty;
        public string processRouteName { get; set; } = string.Empty;
        public DateTime? createdTime { get; set; }
        public DateTime? lastUpdatedTime { get; set; }
        public int itemCount { get; set; }
    }
} 